package com.example.backend.repository;

import com.example.backend.domain.entity.TicketHistory;
import com.example.backend.domain.enums.TicketActionType;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.Instant;
import java.util.List;

@Repository
public interface TicketHistoryRepository extends JpaRepository<TicketHistory, Long> {
    
    List<TicketHistory> findByTicketIdOrderByCreatedAtDesc(Long ticketId);
    
    Page<TicketHistory> findByTicketIdOrderByCreatedAtDesc(Long ticketId, Pageable pageable);
    
    List<TicketHistory> findByTicketIdAndActionTypeOrderByCreatedAtDesc(Long ticketId, TicketActionType actionType);
    
    @Query("SELECT h FROM TicketHistory h WHERE h.ticket.id = :ticketId AND h.createdAt >= :startDate AND h.createdAt <= :endDate ORDER BY h.createdAt DESC")
    List<TicketHistory> findByTicketIdAndDateRange(@Param("ticketId") Long ticketId, 
                                                   @Param("startDate") Instant startDate, 
                                                   @Param("endDate") Instant endDate);
    
    @Query("SELECT h FROM TicketHistory h WHERE h.operator.id = :operatorId ORDER BY h.createdAt DESC")
    Page<TicketHistory> findByOperatorId(@Param("operatorId") Long operatorId, Pageable pageable);
    
    @Query("SELECT COUNT(h) FROM TicketHistory h WHERE h.ticket.id = :ticketId AND h.actionType = :actionType")
    Long countByTicketIdAndActionType(@Param("ticketId") Long ticketId, @Param("actionType") TicketActionType actionType);
}
